﻿using System;
using System.Data;
using System.Data.Objects;
using Soleil.Domain.Core.Repositories;

namespace Infrastructure.Data.EF.Core.Repositories
{
    public class EFUnitOfWork : IUnitOfWork<ObjectContext>
    {
        private bool disposed;

        public EFUnitOfWork(ObjectContext dbContext)
        {
            DbContext = dbContext;
        }

        

        public void Commit()
        {
            DbContext.SaveChanges(SaveOptions.DetectChangesBeforeSave);
        }

        public void Rollback()
        {
            foreach (var entry in DbContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added))
            {
                if(entry.Entity != null)
                    DbContext.DeleteObject(entry.Entity);
            }

            foreach (var entry in DbContext.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
            {
                if(entry.Entity != null)
                    DbContext.Refresh(RefreshMode.StoreWins, entry.Entity);
            }

            foreach (var entry in DbContext.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))
            {
                if(entry.Entity != null)
                    DbContext.Refresh(RefreshMode.StoreWins, entry.Entity);
            }

            DbContext.AcceptAllChanges();
        }

        public ObjectContext DbContext { get; private set; }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    DbContext.Dispose();
                }
                disposed = true;
            }
        }
    }
}
